package com.ywz.project.data.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ywz.common.ResultResp;
import com.ywz.common.StringUtils;
import com.ywz.common.TreeListUtils;
import com.ywz.project.base.data.entity.TDataNationArea;
import com.ywz.project.base.data.service.ITDataNationAreaService;
import com.ywz.project.data.dto.req.NationAreaEditReq;
import com.ywz.project.data.dto.req.NationAreaTreeListPageReq;
import com.ywz.project.data.service.NationAreaApiService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class NationAreaApiServiceImpl implements NationAreaApiService {
    @Resource
    private ITDataNationAreaService itDataNationAreaService;
    private final String NATION_AREA_TREE_LIST_KEY = "SAAS_NATION_AREA_TREE_LIST_KEY";
    @Resource
    private RedisTemplate<String, List<TDataNationArea>> redisTemplate;

    @Override
    public ResultResp getNationAreaTreeListPage(NationAreaTreeListPageReq req) {
        List<TDataNationArea> tChains;
        if (Boolean.TRUE.equals(redisTemplate.hasKey(NATION_AREA_TREE_LIST_KEY))) {
            tChains = redisTemplate.opsForValue().get(NATION_AREA_TREE_LIST_KEY);
        } else {
            tChains = TreeListUtils.listToTree(itDataNationAreaService.list(), TDataNationArea.class, "id", "parentId", 10000000, "children");
            redisTemplate.opsForValue().set(NATION_AREA_TREE_LIST_KEY, tChains, 4, TimeUnit.HOURS);
        }
        if (TreeListUtils.isEmpty(tChains)) return ResultResp.error("数据为空");
        Page<TDataNationArea> page = new Page<>(req.getPageNum(), req.getPageSize());
        // 根据地名过滤
        if (!StringUtils.isEmpty(req.getName())) {
            TDataNationArea filterChina = TreeListUtils.filterTreeByExistsFieldValue(tChains, TDataNationArea.class, "name", req.getName(), "children");
            tChains.clear();
            tChains.add(filterChina);
        }
        // 分页
        page.setTotal(tChains.size());
        page.setRecords(tChains.subList((req.getPageNum() - 1) * req.getPageSize(), Math.min(req.getPageNum() * req.getPageSize(), tChains.size())));
        return ResultResp.success(page);
    }

    @Override
    public ResultResp getNationAreaTreeList() {
        if (Boolean.TRUE.equals(redisTemplate.hasKey(NATION_AREA_TREE_LIST_KEY))) {
            List<TDataNationArea> chinaTreeList = redisTemplate.opsForValue().get(NATION_AREA_TREE_LIST_KEY);
            return ResultResp.success(chinaTreeList);
        }
        List<TDataNationArea> tChains = TreeListUtils.listToTree(itDataNationAreaService.list(), TDataNationArea.class, "id", "parentId", 10000000, "children");
        redisTemplate.opsForValue().set(NATION_AREA_TREE_LIST_KEY, tChains, 4, TimeUnit.HOURS);
        return ResultResp.success(tChains);
    }

    @Override
    public ResultResp editNationArea(NationAreaEditReq req) {
        // 校验参数
        if (StringUtils.isEmpty(req.getName()))
            return ResultResp.error("地区名为空");
        if (!StringUtils.isNumeric(req.getType()))
            return ResultResp.error("地区类型错误");
        if (!StringUtils.isNumeric(req.getLongitude()))
            return ResultResp.error("经度错误");
        if (!StringUtils.isNumeric(req.getLatitude()))
            return ResultResp.error("纬度错误");
        if (StringUtils.isNull(req.getCode(), req.getPid()))
            return ResultResp.error("code和pid参数为空");
        if (StringUtils.isOverLength(255, req.getName(), req.getType(), req.getLongitude(), req.getLatitude()))
            return ResultResp.error("参数长度超过限制");
        // 如果pid不是最高级则验证是否有对应的父级
        if (req.getPid() != 10000000) {
            TDataNationArea tbNationArea = itDataNationAreaService.getById(req.getPid());
            if (tbNationArea == null)
                return ResultResp.error("父级不存在");
        }

        // 保存数据
        TDataNationArea tbNationArea = new TDataNationArea();
        BeanUtils.copyProperties(req, tbNationArea);
        boolean saved = itDataNationAreaService.saveOrUpdate(tbNationArea);
        if (saved)
            redisTemplate.delete(NATION_AREA_TREE_LIST_KEY);
        return saved ? ResultResp.success() : ResultResp.error();
    }

    @Override
    public ResultResp deleteNationArea(Integer id) {
        if (StringUtils.isNull(id))
            return ResultResp.error("参数为空");
        boolean removed = itDataNationAreaService.removeById(id);
        if (removed)
            redisTemplate.delete(NATION_AREA_TREE_LIST_KEY);
        return removed ? ResultResp.success() : ResultResp.error();
    }

}
